package com.lwj.diao;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class WebThreads {
    public static InputStream iis = null;
    public static Map<String, WebThread> threads = new HashMap<String, WebThread>();

    public static String parseExecuteResult(String source) throws InterruptedException {
        String codeId = "T" + System.currentTimeMillis();
        WebThread webThread = new WebThread(WebThreads.classHandle(source));
        webThread.inputInit();
        iis = webThread.iis;
        webThread.init();
        threads.put(codeId, webThread);
        webThread.start();
        Thread.sleep(100L);
        return WebThreads.getResult(codeId, webThread);
    }

    private static String getResult(String codeId, WebThread webThread) {
        String result = Htmls.readPrintLog(webThread.bos);
        webThread.bos.reset();
        webThread.inputStr = null;
        if (webThread.isEnd) {
            webThread.isEnd = false;
            threads.remove(codeId);
            return result;
        }
        if (webThread.isExce) {
            return "error:--->" + result;
        }
        return result + "--<>--" + codeId;
    }

    public static String subValue(String codeId, String val) throws InterruptedException {
        WebThread webThread = threads.get(codeId);
        if (webThread == null) {
            return "\u7a0b\u5e8f\u5df2\u7ed3\u675f";
        }
        System.setOut(webThread.exePrintStream);
        System.setErr(webThread.exePrintStream);
        webThread.inputStr = val.getBytes();
        Thread.sleep(50L);
        return WebThreads.getResult(codeId, webThread);
    }

    private static String classHandle(String source) {
        if (source.indexOf("System.in") > -1) {
            source = source.replace("System.in", "WebThreads.iis");
        }
        return source;
    }
}
